<?php
namespace App\Services;

use App\Repositories\Goods\CategoryModel;
use App\Repositories\Goods\GoodsModel;

class GoodsService
{
    private static $categoryModel;
    private static $goodsModel;

    /**
     * GoodsService constructor.
     * @param CategoryModel $categoryModel
     * @param GoodsModel $goodsModel
     */
    public function __construct(CategoryModel $categoryModel, GoodsModel $goodsModel)
    {
        self::$categoryModel = $categoryModel;
        self::$goodsModel = $goodsModel;
    }

    public function getList($params)
    {
        $cat_id = $params['cat_id'];
        // 获取轮播图
        $where = [
            ['cat_id', '=', $cat_id],
            ['start_time', '<=', time()],
            ['end_time', '>=', time()],
        ];
        $select = ['goods_name', 'market_price', 'goods_remark','shop_price','sales_sum'];
        $result = self::$goodsModel->getAllData($where, $select, 'id', 'DESC');
        $data = array_splice($result, ($params['page'] - 1) * 10,10);

        return $data;
    }

    /**
     * 获取商品详情
     * User: zhouyao
     * Date: 2018/8/28
     * Time: 下午11:22
     * @param $params
     * @throws \App\Exceptions\AppException
     */
    public function goodsDetail($params)
    {
        if (empty($params) || !isset($params['id'])) {
            app_fail(9777);
        }

        // 获取商品信息
        $goods = self::$goodsModel->getOneData($params['id']);
        if(empty($goods) || ($goods['is_on_sale'] == 0) || ($goods['is_virtual']==1 && $goods['virtual_indate'] <= time())){
            app_fail(8999);
        }

        $goods_images_list = M('GoodsImages')->where("goods_id", $goods_id)->select(); // 商品 图册
        $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
        $goods_attr_list = M('GoodsAttr')->where("goods_id", $goods_id)->select(); // 查询商品属性表
    }


    /**
     * 获取商品规格
     * @param $goods_id|商品id
     * @return array
     */
    public function get_spec($goods_id)
    {
        //商品规格 价钱 库存表 找出 所有 规格项id
        $keys =  app('db')->table('SpecGoodsPrice')->where("goods_id", $goods_id)->getField("GROUP_CONCAT(`key` ORDER BY store_count desc SEPARATOR '_') ");
        $filter_spec = array();
        if ($keys) {
            $specImage =  app('db')->table('SpecImage')->where(['goods_id'=>$goods_id,'src'=>['<>','']])->getField("spec_image_id,src");// 规格对应的 图片表， 例如颜色
            $keys = str_replace('_', ',', $keys);
            $sql = "SELECT a.name,a.order,b.* FROM spec AS a INNER JOIN spec_item AS b ON a.id = b.spec_id WHERE b.id IN($keys) ORDER BY b.id";
            $filter_spec2 = app('db')->query($sql);
            foreach ($filter_spec2 as $key => $val) {
                $filter_spec[$val['name']][] = array(
                    'item_id' => $val['id'],
                    'item' => $val['item'],
                    'src' => $specImage[$val['id']],
                );
            }
        }
        return $filter_spec;
    }

    /**
     * 商品列表
     * User: zhouyao
     * Date: 2018/8/26
     * Time: 下午5:34
     * @param $params
     * @return array
     * @throws \App\Exceptions\AppException
     */
    public function goodsList($params)
    {
        if (empty($params) || !isset($params['page']) || !isset($params['limit'])) {
            app_fail(9997);
        }

        // 排序设置
        $sort = !isset($params['sort']) ? 'asc' : $params['sort'];
        $orderByName = !isset($params['orderByName']) ? 'click_count' : $params['orderByName'];

        // 显法当前商品分类名称
        $goodsCate = self::$categoryModel->getOneData(['id' => $params['cate_id']], ['name']);
        // 获取该分类 id 及下面的所有子分类 id
        $cat_id_arr = getCatGrandson($params['cate_id']);
        // 显示商品列表
        $goods_where = ['is_on_sale' => 1, 'exchange_integral' => 0];
        $filter_goods_id = self::$goodsModel->getWhereInDataPluck($goods_where, 'cat_id', $cat_id_arr, 'goods_id');
        // TODO 商品筛选条件

        // 获取商品总数
        $count = count($filter_goods_id);
        $data = []; // 商品列表集合
        if ($count > 0) {
            $goodsList = self::$goodsModel->getWhereInPageData($params['page'], $params['limit'], '', $orderByName, $sort, 'goods_id', $filter_goods_id);
            $data = collect($goodsList)->map(function ($item) use ($data) {
                $data = [
                    'url' => $item->original_img,
                    'id' => $item->goods_id,
                    'link' => $item->goods_id,
                    'hot' => $item->is_hot,
                    'englishName' => $item->goods_name,
                    'chinaName' => mb_substr($item->goods_remark, 0, 20, 'utf-8'),
                    'price' => $item->shop_price,
                    'oldprice' => $item->market_price,
                    'discount' => round($item->shop_price / $item->market_price * 10, 2),
                ];
                return $data;
            });
        }
        return [
            'goodsList' => $data,
            'goodsCateName' => !isset($goodsCate->name) ? '' : $goodsCate->name,
        ];
    }
}